/*
Copyright 2016 S7connector members (github.com/s7connector)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.cnbm.wcsbasic.protocol.netty.s7.s7connector.impl.nodave;

import com.cnbm.wcsbasic.protocol.netty.s7.s7connector.exception.S7IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public final class PLCinterface {
	InputStream in;
	int localMPI; // the adapter's MPI address
	String name;

	OutputStream out;
	int protocol; // The kind of transport used on this interface.
	int wp, rp;
	private static final Logger logger = LoggerFactory.getLogger(PLCinterface.class);
	public PLCinterface(final OutputStream out, final InputStream in, final String name, final int localMPI,
			final int protocol) {
		this.init(out, in, name, localMPI, protocol);
	}

	public void init(final OutputStream oStream, final InputStream iStream, final String name, final int localMPI,
			final int protocol) {
		this.out = oStream;
		this.in = iStream;
		this.name = name;
		this.localMPI = localMPI;
		this.protocol = protocol;
	}


	//todo 待定，这里我改一下
	public int read(final byte[] b, int start, int len){
		int res;
		try {
			int retry = 0;
			//while ((this.in.available() <= 0) && (retry < 500)) {
			//如果网络延迟比较大 改下这里（如果把这个数值改大了，那么性能会降低），主要用于判断 网络有没有断开
			while ((this.in.available() <= 0) && (retry < 500)) {
				try {
					if (retry > 0) {
						Thread.sleep(1);
					}
					retry++;
				} catch (final InterruptedException e) {
					logger.info("Socket read wait字节流失败，in.available: "+this.in.available()+" ,retry: "+retry+" , errMsg: "+e);
				}
			}
			res = -1;
			while ((this.in.available() > 0) && (len > 0)) {
				res = this.in.read(b, start, len);
				start += res;
				len -= res;
			}
			return res;
		} catch (final IOException e) {
			String errMsg = "Socket read字节流失败: "+e.getMessage();
			logger.info(errMsg);
			throw new S7IOException(errMsg);
		}
	}

//	public int read(final byte[] b, int start, int len){
//		int res;
//		if(len<=0){
//			throw new S7IOException("要读取的 len<=0 ");
//		}
//		try {
//			int retry = 0;
//			while ((this.in.available() <= len) && (retry < 1000)) {
//				try {
//					if (retry > 0) {
//						Thread.sleep(1);
//					}
//					retry++;
//				} catch (final InterruptedException e) {
//					logger.info("Socket read wait字节流 超时，in.available: "+this.in.available()+" ,retry: "+retry+" , errMsg: "+e);
//				}
//			}
//			res = -1;
//			while ((this.in.available() > 0) && (len > 0)) {
//				res = this.in.read(b, start, len);
//				start += res;
//				len -= res;
//			}
//			return res;
//		} catch (final IOException e) {
//			String errMsg = "Socket read字节流失败: "+e.getMessage();
//			logger.info(errMsg);
//			throw new S7IOException(errMsg);
//		}
//	}

	/**
	 * return :
	 * 		1 成功
	 * 	    0 失败
	 * */
	public int write(final byte[] b, final int start, final int len){
		try {
			this.out.write(b, start, len);
			return 1;
		} catch (final IOException e) {
			String errMsg = "Socket write字节流失败: "+e.getMessage();
			logger.info(errMsg);
			throw new S7IOException(errMsg);
		}
	}

}
